#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

void send_login(int socket_fd, const char* username, const char* password) {
    char data[200];
    snprintf(data, sizeof(data), "login: %s password: %s", username, password);
    send(socket_fd, data, strlen(data), 0);
}

void send_register(int socket_fd, const char* username, const char* password) {
    char data[200];
    snprintf(data, sizeof(data), "register: %s password: %s", username, password);
    send(socket_fd, data, strlen(data), 0);
}

void send_data(int socket_fd) {
    FILE* pf = fopen("1.txt", "r");
    long long  msg[3] = {0};
    long long da=0;
    float tm=0;
    float hu=0;
    if (pf != NULL) {
        while (fscanf(pf, "%lld %f %f", &da, &tm, &hu) != EOF) {
            // 在这里处理日期和时间
            msg[0]=da;
            msg[1]=tm;
            msg[2]=hu;
            if(send(socket_fd, msg, sizeof(msg), 0) < 0) {
                perror("send failed");
                exit(-2);
            }
            printf("消息已发送\n");
        }
    } else {
        perror("open\n");
        exit(-1);
    }    
}

int main(int argc, char *argv[]) {
    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd < 0) {
        perror("socket creation failed");
        return -1;
    }

    struct sockaddr_in srvaddr;
    srvaddr.sin_family = AF_INET;
    srvaddr.sin_port = htons(55555);
    srvaddr.sin_addr.s_addr = inet_addr("192.168.64.7");

    if(connect(socket_fd, (struct sockaddr *)&srvaddr, sizeof(srvaddr)) < 0) {
        perror("connect failed");
        return -1;
    }

    printf("连接成功\n");

    char choice[10];
    printf("Do you want to register or login? ");
    fgets(choice, sizeof(choice), stdin);
    choice[strcspn(choice, "\n")] = 0;

    char username[1024];
    printf("Enter username: ");
    fgets(username, sizeof(username), stdin);
    username[strcspn(username, "\n")] = 0;

    char password[1024];
    printf("Enter password: ");
    fgets(password, sizeof(password), stdin);
    password[strcspn(password, "\n")] = 0;

    if (strncmp(choice, "register", 8) == 0) {
        send_register(socket_fd, username, password);
    } else if (strncmp(choice, "login", 5) == 0) {
    send_login(socket_fd, username, password);
    // 接收服务器的确认消息
    char buffer[1024];
    recv(socket_fd, buffer, sizeof(buffer), 0);
    if (strncmp(buffer, "Login successful", 16) == 0) {
        printf("已经接收登录成功，开始发送\n");
        // 如果接收到登录成功的确认消息，发送温湿度数据
        send_data(socket_fd);
    }
}

    close(socket_fd);

    return 0;
}
